package tenglang.zuul.zuul;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import tenglang.zuul.config.ZuulFilterProperties;
import tenglang.zuul.zuul.filter.AuthFilter;

import java.util.Properties;
import java.util.concurrent.Executor;

@Configuration
@Import({NewZuulConfig.class})
public class NacosServerConfig {

    @Value("${spring.cloud.nacos.config.server-addr}")
    private String serverAddr;

    @Autowired
    NewZuulRouteLocator routeLocator;

    @Autowired
    private ZuulFilterProperties zuulFilterProperties;

    @Autowired
    ApplicationEventPublisher publisher;

    @Bean
    public ConfigService configService(){
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        try {
            ConfigService configService = NacosFactory.createConfigService(properties);
            configService.addListener(ZuulConstant.NACOS_DATA_ID, ZuulConstant.NACOS_GROUP_ID, new Listener() {
                @Override
                public Executor getExecutor() {
                    //可以发送监听消息到某个MQ
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println("Nacos更新了！");
                    //切忌！！！不需要自己去刷新
                    RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
                    publisher.publishEvent(routesRefreshedEvent);
                }
            });

            configService.addListener(zuulFilterProperties.getAppsDataId(), zuulFilterProperties.getAppsGroup(), new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }
                @Override
                public void receiveConfigInfo(String configInfo) {
                    AuthFilter.update(configInfo,zuulFilterProperties.getAppsDataId(),zuulFilterProperties.getAppsGroup());
                }
            });
            return configService;
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }

}
